# -*- encoding: utf-8 -*-

"""
@File:      tc_readline_fun_005.py
@Time:      2024-02-29 15:30:00
@Author:    qintingting
@Version:   1.0
@Contact:   wb-qtt862918@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    qintingting
"""
from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_readline_fun_005.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "readline readline-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline='''cat > readline_fun_005.c <<EOF
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>

int main() {
    // 初始化历史记录
    using_history();

    // 添加一些历史记录
    add_history("First command");
    add_history("Second command");
    add_history("Third command");
    add_history("Fourth command");
    
    // 打印当前历史记录数目
    int original_number = history_length;
    printf("Original history length: %d\\n", original_number);
    
    // 限制历史记录数目为2
    stifle_history(2);
    
    // 获取并打印当前历史记录
    HIST_ENTRY **my_history_list = history_list(); // 修改变量名以避免冲突
    if (my_history_list) {
        int i = 0;
        while (my_history_list[i]) { // 使用新的变量名进行迭代
            printf("%d: %s\\n", i + 1, my_history_list[i]->line);
            ++i;
        }
    }
    
    // 打印经过限制后的历史记录数目
    int new_number = history_length;
    printf("Stifled history length: %d\\n", new_number);

    // 清除历史记录并退出
    clear_history();
    return 0;
}
EOF
'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o readline_fun_005 readline_fun_005.c -lhistory -lreadline")
        code, result = self.cmd("file readline_fun_005")
        self.assertIn("executable", result)
        code, result = self.cmd("./readline_fun_005")
        self.assertIn("Original history length: 4", result)
        self.assertIn("Stifled history length: 2", result)
         
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf readline_fun_005 readline_fun_005.c")